//
//  GameCenterController.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/4.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage
import SafariServices

class GameCenterController: BaseViewController {
    
    var image : UIImage?
    
    var bigImageUrl = "-999"
    
    var game_banner_url = "-999"
    
    var dataModels : [GameListModel]?
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "游戏中心"
        
        weak var weakSelf = self
        
        plainTableView.tableFooterView = UIView()
        
        plainTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }
        
        plainTableView.mj_header.beginRefreshing()
        plainTableView.register(UINib(nibName: StringFromClass(classType: GameCenterTopCell.self), bundle: nil), forCellReuseIdentifier: GameCenterTopCell.identifer())

        plainTableView.register(UINib(nibName: StringFromClass(classType: GameCenterListCell.self), bundle: nil), forCellReuseIdentifier: GameCenterListCell.identifer())

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

   
}


extension GameCenterController{
    func loadData(){
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=games&a=get_list", parameters: nil) {[weak self] (responseObject, error) in
            
            
            if error == nil {
                
                self?.bigImageUrl = responseObject!["game_banner"] as! String
                
                self?.game_banner_url = responseObject!["game_banner_url"] as! String
                
                self?.dataModels = [GameListModel]()
                
                
                
                for dic in responseObject!["datas"]!["list"] as! [[String : AnyObject]]{
                    
                    self!.dataModels!.append(GameListModel(dic: dic))
                    
                }
                
                
                
                
                if self!.dataModels!.count == 0{
                    
                    self?.showLogoView(text : "暂无游戏下载...")
                    
                    self!.plainTableView.mj_header.endRefreshing()
                    
                }else{
                    
                    self!.cachePictures()
                    
                }
                
                
                
                
                
            }else{
                
                self!.plainTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
            
            
            
        }
        
        
        
        
    }
    
    
    
    
    
    
    func cachePictures(){
        
        let url = URL(string: bigImageUrl)
        
        if url == nil {
            
            self.plainTableView.mj_header.endRefreshing()
            
            
            self.plainTableView.reloadData()
            
            return
        }
        
        
        
        let grop = DispatchGroup()
        
        
        
        grop.enter()
        
        SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
            
            grop.leave()
            
        })
        
        
        
        
        grop.notify(queue: DispatchQueue.main) {
            
            
            if let imageCach = SDWebImageManager.shared().imageCache {
                
                if let temp = imageCach.imageFromDiskCache(forKey: self.bigImageUrl) {
                
                self.image = temp
                
                }
            
            
            }
            
            
            self.plainTableView.mj_header.endRefreshing()
            
            
            self.plainTableView.reloadData()
            
            
            
        }
        
        
        
        
    }







}





extension GameCenterController{



    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        if dataModels!.count > 0 {
            return 2
        } else {
            return 0
        }
        
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
       
        if section == 0 {
            return 1
        } else {
            return dataModels?.count ?? 0
        }
    
    
    }
    
    
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let tableCell : UITableViewCell!
        
        if indexPath.section == 0 {
            
            let temp = tableView.dequeueReusableCell(withIdentifier: GameCenterTopCell.identifer()) as! GameCenterTopCell
            
            temp.viewImage = image
            
            tableCell = temp
            
        } else {
            
            let temp = tableView.dequeueReusableCell(withIdentifier: GameCenterListCell.identifer()) as! GameCenterListCell
            
            temp.model = dataModels?[indexPath.row]
            
            tableCell = temp
        }
        
        
        return tableCell
        
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        if indexPath.section == 0 {

            
            if game_banner_url.components(separatedBy: "xz.qzyds.com").count > 1 {
                let urlStr = URL(string: game_banner_url)
                
                if urlStr == nil {
                    return
                }
                
                if #available(iOS 9.0, *) {
                    
                    let temp = SFSafariViewController(url: urlStr!)
                    present(temp, animated: true, completion: nil)
                    
                } else {
                    
                    if UIApplication.shared.canOpenURL(urlStr!) {
                        
                        UIApplication.shared.openURL(urlStr!)
                        
                        
                    }
                    
                    
                }
                
                
                
            }else if game_banner_url.components(separatedBy: "mall.xjscvip.com").count > 1{
            
                let temp = UpLoadIconController()
                
                temp.urlStr = game_banner_url
                
                navigationController?.pushViewController(temp, animated: true)

            
            }else{
            
            
                let temp = UpLoadIconController()
                
                temp.hiddenBar = false
                
                temp.urlStr = game_banner_url
                
                navigationController?.pushViewController(temp, animated: true)

            
            
            }

            
            
        } else {
            
            let temp = GameDetailController()
            
            temp.gameId = dataModels![indexPath.row].game_id
            
            
            navigationController?.pushViewController(temp, animated: true)
            
        }
        
        
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            
            if image == nil {
                return KScreenW / 16 * 8
            } else {
                return image!.size.height / image!.size.width * KScreenW
            }
            
        } else {
            return 80
        }
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        
        return 0.00001

        
    }
    
    
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        
        if section == 0 {
            
            return 0.00001
            
        } else {
            
            return 36
            
        }
        
    }
    
    
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        
        
        if section == 0 {
            
            return ""
            
        } else {
            
            
            return "推荐游戏"
            
        }
        
        
    }




}
